<?php

namespace app\wechat\controllers;

use app\wechat\core\BaseController;
use app\wechat\interfaces\UserInterface;
use app\wechat\models\UserModel;
use cm;
use common\models\User;
use common\models\UserBalance;
use common\models\UserBindLog;
use common\models\UserRebate;
use Yii;
use Exception;

class UserController extends BaseController implements UserInterface
{
    /*
    * 获取常用联系人
    */
    function actionInfo()
    {
        return (new UserModel())->actionInfo();
    }

    /*
    * 获取常用联系人
    */
    function actionContacts()
    {
        return (new UserModel())->actionContacts();
    }

    /*
    * 添加常用联系人
    */
    function actionAddcontacts()
    {
        return (new UserModel())->actionAddcontacts();
    }

    /*
    * 编辑常用联系人
    */
    function actionEditcontacts()
    {
        return (new UserModel())->actionEditcontacts();
    }

    /*
    * 删除常用联系人
    */
    function actionDelcontacts()
    {
        return (new UserModel())->actionDelcontacts();
    }

    /*
    *添加意见反馈
    */
    function actionAddfeedback(){
        return (new UserModel())->actionAddfeedback();    
    }

    /*
    *上传
    */
    function actionUpload(){
        return (new UserModel())->actionUpload();
    }
       
    /*        
    *个人中心
    */
    function actionPersonal(){
        return (new UserModel())->actionPersonal();  
    }

    /*        
    *个人中心
    */
    function actionSaveinfo(){
        return (new UserModel())->actionSaveinfo();  
    }

    public function getOpenid(){
        $openid=defined("WX_OPENDID") ? WX_OPENDID : '';
        if($openid=='')throw new Exception('登录失效');
        return $openid;
    }

    /**
     * 绑粉
     */
    public function actionBind(){
        $transaction=Yii::$app->db->beginTransaction();
        try {
            $params=Yii::$app->request->post();
            if(empty($params['uid']))throw new Exception('参数错误');
            $user=User::findOne($params['uid']);
            if(!$user)throw new Exception('用户不存在');
            $model=User::find()->andWhere(['openid'=>$this->getOpenid()])->one();
            if(!$model)throw new Exception('系统异常');
            if($params['uid']==$model->id)Cm::$res->susess([],'不能绑定自己');
            $model->bind_uid=$params['uid'];
            if(!$model->save())throw new Exception('操作失败'.current($model->getFirstErrors()));
            $log=new UserBindLog();
            $log->uid=$model->id;
            $log->bind_uid=$params['uid'];
            if(!$log->save())throw new Exception('操作失败'.current($log->getFirstErrors()));
            $transaction->commit();
            Cm::$res->susess([],'绑粉成功');
        }catch(Exception $e){
            $transaction->rollBack();
            Cm::$res->error($e->getMessage());
        }
    }

    /**
     * 余额明细
     */
    public function actionRebate(){
        try {
            $params=Yii::$app->request->post();
            $model=User::find()->andWhere(['openid'=>$this->getOpenid()])->one();
            $query=UserRebate::find()
                ->with(['order'=>function($q){
                    $q->select(['id','order_number','addtime','pay_time']);
                }])->andWhere(['uid'=>$model->id]);
            if(!empty($params['type']))$query->andWhere(['type'=>$params['type']]);
            if(!empty($params['created_at'])){
                $created_at=explode('~',$params['created_at']);
                $query->andWhere(['between','created_at',strtotime($created_at[0]),strtotime($created_at[1])]);
            }
            if(!empty($params['status']))$query->andWhere(['status'=>$params['status']]);

            $data['total']=$query->count();
            $size = empty($params['size'])?10:$params['size'];
            $page=empty($params['page'])?1:$params['page'];
            $data['data']=$query->limit($size)->offset(($page - 1) * $size)->asArray()->all();
            Cm::$res->susess($data,'获取成功');
        }catch (Exception $e){
            Cm::$res->error($e->getMessage());
        }
    }

    /**
     * 提现
     * @throws \yii\db\Exception
     */
    public function actionBalance(){
        $transaction=Yii::$app->db->beginTransaction();
        try {
            $params=Yii::$app->request->post();
            if(empty($params['money']))throw new Exception('请输入金额');
            $model=User::find()->andWhere(['openid'=>$this->getOpenid()])->one();
            $balance=UserBalance::getBalance($model->id);
            $params['money']=sprintf("%.2f", $params['money']);
            if($params['money']<=0)throw new Exception('金额错误，请从新输入');

            if($balance<$params['money'])throw new Exception('余额不足');
            $after_money=sprintf("%.2f",$balance-$params['money']);
            if($after_money<0)throw new Exception('余额不足');

            $rebate_model=new UserRebate();
            $rebate_model->uid=$model->id;
            $rebate_model->type=UserRebate::TYPE_DRAW;
            $rebate_model->money=$params['money'];
            $rebate_model->date_ym=date('Ym');
            $rebate_model->date_ymd=date('Ymd');
            $rebate_model->status=UserRebate::STATUS_AUDIT;
            $rebate_model->after_money=$after_money;
            if(!$rebate_model->save())throw new Exception('余额扣除失败');
            UserBalance::DeductBalance($model->id,$params['money']);
            $transaction->commit();
            Cm::$res->susess([],'操作成功,等待审核');
        }catch (Exception $e){
            $transaction->rollBack();
            Cm::$res->error($e->getMessage());
        }
    }

}